package cn.kjcoder.redis.controller;

import cn.kjcoder.redis.domain.Cart;
import cn.kjcoder.redis.domain.CartPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2022/1/20
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@RestController
@Slf4j
@RequestMapping("/cart")
public class UserCartController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 购物车key的前缀
     */
    public static final String CART_KEY = "cart:user:";

    /**
     * 添加购物车
     */
    @PostMapping("/addCart")
    public void addCart(Cart cart){
        String key = CART_KEY + cart.getUserId();
        Boolean hasKey = this.redisTemplate.opsForHash().getOperations().hasKey(key);
        if(hasKey){
            this.redisTemplate.opsForHash().put(key,cart.getProductId().toString(),cart.getAmount());
        }else{
            this.redisTemplate.opsForHash().put(key,cart.getProductId().toString(),cart.getAmount());
            this.redisTemplate.expire(key,90, TimeUnit.DAYS);
        }
        //TODO 发送mq进行异步添加商品到数据库中
    }

    /**
     * 修改购物车的数量
     */
    @PostMapping("/updateCart")
    public void updateCart(Cart cart){
        String key = CART_KEY + cart.getUserId();
        this.redisTemplate.opsForHash().put(key,cart.getProductId().toString(),cart.getAmount());
        //TODO 发送mq进行异步更新数据库商品的数量
    }

    /**
     * 删除购物车商品
     */
    @PostMapping("/delCart")
    public void delCart(Long userId,Long productId){
        String key = CART_KEY + userId;
        this.redisTemplate.opsForHash().delete(key,productId.toString());
        //TODO 发送mq进行数据库商品的删除
    }

    /**
     * 查询购物车所有商品
     */
    @PostMapping("/findAll")
    public CartPage findAll(Long userId){
        String key = CART_KEY + userId;
        CartPage<Cart> cartPage = new CartPage();
        //查询购物车的总数
        long size = this.redisTemplate.opsForHash().size(key);
        cartPage.setCount((int)size);

        //查询购物车所有商品
        Map<String,Integer> map = this.redisTemplate.opsForHash().entries(key);
        List<Cart> list = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            Cart cart  = new Cart();
            cart.setUserId(userId);
            cart.setAmount(entry.getValue());
            cart.setProductId(Long.parseLong(entry.getKey()));
            list.add(cart);
        }
        cartPage.setCartList(list);
        return cartPage;
    }

}
